import { useEffect, useState } from "react";
import { Input, message, Spin, Form } from "antd";
import {
  Card,
  Button,
  Drawer,
  Menu,
  Message,
  Modal,
  Select,
} from "@arco-design/web-react";
import { PlusOutlined } from "@ant-design/icons";
import { useStore } from "@/store";
import { nanoid } from "nanoid";
import { getRequest, postRequest, putRequest } from "@/request";
import SessionStorageService from "@/SessionStorageService";
import { CommonPPT } from "@/components/CommonPPT";

// import SuoLueTu from "./SuoLueTu";
import { useNavigate } from "react-router-dom";

const PPTDisplayList = () => {
  const {
    powerPointParArr,
    modifyPowerPoint,
    updatePowerPointIndex,
    modifyPowerPointTitle,
    modifyArbitraryValue,
  } = useStore();
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [storeData, setStoreData] = useState(null);
  const [form] = Form.useForm();
  const PPtBgtypeWatch = Form.useWatch("PPtBgtype", form);
  const navigate = useNavigate();
  console.log("列表页的slideFatnerList:", powerPointParArr, storeData);

  const queryData = () => {
    setLoading(true);
    getRequest("/store", {}).then((data) => {
      setLoading(false);
      console.log("store响应数据:", data);
      // eslint-disable-next-line
      if (data && data?.hasOwnProperty("store")) {
        if (data?.store && data?.store?.length > 0) {
          // 有值的情况
          modifyArbitraryValue({
            powerPointParArr: data?.store || [],
            powerPointParId: "",
          });
          setStoreData(data?.store);
          SessionStorageService.setItem("store", data?.store);
          updatePowerPointIndex(1);
        } else {
          // 无值的情况
          modifyArbitraryValue({
            powerPointParArr: [],
            powerPointParId: "",
          });
          modifyPowerPoint([
            {
              sortId: 1,
              id: nanoid(),
              elements: [],
            },
          ]);
          modifyPowerPointTitle("");
          updatePowerPointIndex(1);
        }
      } else {
        message.error("请先进行登录");
        navigate("/login");
      }
    });
  };

  useEffect(() => {
    setTimeout(() => {
      if (SessionStorageService.getItem("token")) {
        queryData();
      } else {
        Message.error("请先进行登录");
        navigate("/login");
      }
    }, 500);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // const gotoCancle = () => {};

  const handleCancel = () => {
    setModalVisible(false);
  };

  const handleOK = () => {
    form.validateFields().then((values) => {
      console.log("表单数据:", values);
      setModalVisible(false);
      const id = nanoid();
      navigate(`/pptDetail?title=${values?.powerPointTitle}`);
      modifyArbitraryValue({
        powerPointParId: id,
        powerPointImage: values?.powerPointImage,
        PPtBgtype: values?.PPtBgtype,
        PPtBgValue1: values?.PPtBgValue1,
        PPtBgValue2: values?.PPtBgValue2,
      });
      handleCancel();
    });
  };

  const handleOut = async () => {
    // 登录
    // 示例POST请求
    postRequest("/admin/auth/logout").then((data) => {
      console.log("POST响应数据:", data);
      // 如果响应数据存在且包含token
      if (data) {
        navigate("/login");
        SessionStorageService.removeItem("token");
        SessionStorageService.removeItem("email");
        // 显示登录成功的消息
        Message.success(`退出登录成功`);
      }
    });
  };

  const handleOperate = (type, childItem, childIndex) => {
    // 编辑
    if (type === "编辑") {
      navigate(
        `/pptDetail?title=${childItem.powerPointTitle}&id=${childItem.id}`
      );
      modifyArbitraryValue({
        powerPointImage: childItem?.powerPointImage,
        PPtBgtype: childItem?.PPtBgtype,
        PPtBgValue1: childItem?.PPtBgValue1,
        PPtBgValue2: childItem?.PPtBgValue2,
      });
    }
    if (type === "预览") {
      window.open(
        `/pptPreview?title=${childItem.powerPointTitle}&id=${childItem.id}`,
        "_blank"
      );
    }
    if (type === "删除") {
      Modal.confirm({
        title: "提示",
        content: "确定要删除此幻灯片吗？",
        onOk: async () => {
          setLoading(true);
          const slideFatnerListBro = powerPointParArr.filter(
            (item, index) => index !== childIndex
          );
          putRequest("/store", { store: slideFatnerListBro }).then(() => {
            setLoading(false);
            Message.success("删除成功");
            queryData();
          });
        },
      });
    }
  };

  // 定义一个名为dropList的函数，接收fatherItem和fatherIndex两个参数
  // eslint-disable-next-line no-unused-vars
  const dropList = (childItem, childIndex) => {
    // 返回一个Menu组件，包含三个Menu.Item组件
    return (
      <Menu>
        {/* 第一个Menu.Item组件，点击时调用handleOperate函数，传入"编辑"和fatherItem、fatherIndex参数，显示"编辑"文字 */}
        <Menu.Item
          key="1"
          onClick={() => {
            handleOperate("编辑", childItem, childIndex);
          }}
        >
          编辑
        </Menu.Item>
        {/* 第二个Menu.Item组件，点击时调用handleOperate函数，传入"预览"和fatherItem、fatherIndex参数，显示"预览"文字 */}
        <Menu.Item
          key="2"
          onClick={handleOperate("预览", childItem, childIndex)}
        >
          预览
        </Menu.Item>
        {/* 第三个Menu.Item组件，点击时调用handleOperate函数，传入"删除"和fatherItem、fatherIndex参数，显示"删除"文字 */}
        <Menu.Item
          key="3"
          onClick={handleOperate("删除", childItem, childIndex)}
        >
          删除
        </Menu.Item>
      </Menu>
    );
  };

  return (
    <div
      style={{
        // 设置宽度为100%
        width: "100%",
        // 设置高度为100%
        height: "100%",
        // 设置内边距为32px
        padding: "32px",
        // 设置上边距为16px
        paddingTop: "16px",
        // 设置垂直滚动条
        overflowY: "scroll",
        // 设置背景颜色为#f3f4f6
        backgroundColor: "#f3f4f6",
      }}
    >
      <div
        // 设置样式
        style={{
          // 外边距为0，自动居中
          margin: "0 auto",
          // 弹性布局
          display: "flex",
          // 宽度为1400
          width: 1400,
          // 主轴为水平方向，项目之间的间隔为平均分布
          justifyContent: "space-between",
          // 下边距为20px
          marginBottom: "20px",
          paddingLeft: 30,
        }}
      >
        <Button
          key="add"
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setModalVisible(true);
          }}
        >
          新建幻灯片
        </Button>
        <Button
          key="退出登录"
          type="dashed"
          onClick={() => {
            handleOut();
          }}
        >
          退出登录
        </Button>
      </div>
      <Spin spinning={loading}>
        <>
          {powerPointParArr && powerPointParArr?.length > 0 ? (
            <>
              <div
                // 设置样式
                style={{
                  // 设置宽度为1300
                  width: 1400,
                  // 设置外边距为0
                  margin: "0 auto",
                  // 设置显示方式为弹性布局
                  display: "flex",
                  // 设置主轴方向为左对齐
                  justifyContent: "left",
                  // 设置换行方式为换行
                  flexWrap: "wrap",
                }}
              >
                {powerPointParArr?.map((childItem, childIndex) => {
                  return (
                    <Card
                      key={childItem?.id}
                      style={{
                        width: "auto",
                        marginLeft: 30,
                        marginBottom: 30,
                      }}
                      title={childItem?.powerPointTitle}
                      hoverable
                      extra={
                        <div style={{ display: "flex" }}>
                          <a
                            style={{ marginRight: 4 }}
                            onClick={() => {
                              handleOperate("编辑", childItem, childIndex);
                            }}
                          >
                            编辑
                          </a>
                          <a
                            style={{ marginRight: 4 }}
                            onClick={() => {
                              handleOperate("删除", childItem, childIndex);
                            }}
                          >
                            删除
                          </a>
                          <a
                            onClick={() => {
                              handleOperate("预览", childItem, childIndex);
                            }}
                          >
                            预览
                          </a>
                        </div>
                      }
                    >
                      <div
                        style={{
                          width: 400,
                          height: 200,
                          overflow: "hidden",
                          background: childItem?.powerPointImage
                            ? `url(${childItem?.powerPointImage}) 0% 0% / cover no-repeat`
                            : "#edf2fa",
                        }}
                      >
                        {childIndex < -1 ? (
                          <div>
                            {childItem?.powerPointArr?.map((items, indexs) => {
                              if (indexs === 0) {
                                return (
                                  <>
                                    <div
                                      key={items.id}
                                      style={{
                                        width: 224,
                                        height: 114,
                                        // border: "1px solid #e8e8e8",
                                        position: "relative",
                                      }}
                                    >
                                      {/* // 创建一个绝对定位的div，宽400，高200，背景色为红色，透明度为0，z-index为2 */}
                                      <div
                                        style={{
                                          // 设置元素的位置为绝对定位
                                          position: "absolute",
                                          // 设置元素的顶部位置为0
                                          top: 0,
                                          // 设置元素的左侧位置为0
                                          left: 0,
                                          // 设置元素的宽度为400
                                          width: 400,
                                          // 设置元素的高度为200
                                          height: 200,
                                          // 设置元素的背景颜色为红色
                                          background: "red",
                                          // 设置元素的透明度为0
                                          opacity: 0,
                                          // 设置元素的层级为2
                                          zIndex: 2,
                                        }}
                                      />
                                      {/* // 创建一个flex布局的div，水平排列，换行，两端对齐，宽1100，高550，自动居中，内边距16，右内边距8，溢出隐藏，背景色为白色，缩放0.35，上边距-176，左边距-352 */}
                                      <div
                                        style={{
                                          // 设置显示方式为弹性布局
                                          display: "flex",
                                          // 设置主轴方向为水平方向
                                          flexDirection: "row",
                                          // 设置换行方式为换行
                                          flexWrap: "wrap",
                                          // 设置主轴方向上的对齐方式为两端对齐
                                          justifyContent: "space-between",
                                          // 设置宽度为1100
                                          width: 1100,
                                          // 设置高度为550
                                          height: 550,
                                          // 设置外边距为自动
                                          margin: "auto",
                                          // 设置内边距为16
                                          padding: 16,
                                          // 设置右边内边距为8
                                          paddingRight: 8,
                                          // 设置溢出方式为隐藏
                                          overflow: "hidden",
                                          // 设置背景颜色为白色
                                          backgroundColor: "white",
                                          // 设置缩放比例为0.35
                                          transform: "scale(0.35)",
                                          // 设置上边距为-176
                                          marginTop: -176,
                                          // 设置左边距为-352
                                          marginLeft: -352,
                                          background:
                                            items?.PPtBgtype == "gradient"
                                              ? `linear-gradient(to bottom right,${items?.PPtBgValue1},${items?.PPtBgValue2})`
                                              : items?.PPtBgtype == "img"
                                              ? `url(${items?.PPtBgValue1}) 0% 0% / cover no-repeat`
                                              : items?.PPtBgValue1 || "#fff",
                                          backgroundSize: "cover", // 设置背景图片大小
                                          backgroundRepeat: "no-repeat", // 设置背景图片不重复
                                        }}
                                      >
                                        <CommonPPT slideListItem={items} />
                                      </div>
                                    </div>
                                  </>
                                );
                              }
                              return null;
                            })}
                          </div>
                        ) : null}
                      </div>
                    </Card>
                  );
                })}
              </div>
            </>
          ) : (
            <div style={{ width: 1400, margin: "auto" }}>
              暂无演示数据，请新建
            </div>
          )}
        </>
      </Spin>
      <Drawer
        width={500}
        title="PPT设置"
        visible={modalVisible}
        onCancel={handleCancel}
        onOk={handleOK}
        okText="创建"
        cancelText="取消"
      >
        <Form
          // 设置表单标签的宽度
          labelCol={{ span: 8 }}
          // 设置表单实例
          form={form}
          // 设置表单的初始值
          initialValues={{
            powerPointTitle: "",
            powerPointImage: "",
            PPtBgtype: "color",
            PPtBgValue1: "",
            PPtBgValue2: "",
          }}
        >
          <Form.Item
            label="标题"
            name="powerPointTitle"
            rules={[{ required: true, message: "不得为空" }]}
          >
            <Input style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item label="缩略图地址" name="powerPointImage">
            <Input style={{ width: "100%" }} />
          </Form.Item>
          {/* <Form.Item
            label="背景类型"
            name="PPtBgtype"
            rules={[{ required: true, message: "不得为空" }]}
          >
            <Select
              style={{ width: "100%" }}
              options={[
                { label: "颜色", value: "color" },
                { label: "渐变", value: "gradient" },
                { label: "图像", value: "img" },
              ]}
            />
          </Form.Item>
          {PPtBgtypeWatch === "color" && (
            <Form.Item
              label="颜色"
              name="PPtBgValue1"
              rules={[{ required: true, message: "不得为空" }]}
            >
              <Input style={{ width: "100%" }} />
            </Form.Item>
          )}
          {PPtBgtypeWatch === "img" && (
            <Form.Item
              label="图像地址"
              name="PPtBgValue1"
              rules={[{ required: true, message: "不得为空" }]}
            >
              <Input style={{ width: "100%" }} />
            </Form.Item>
          )}
          {PPtBgtypeWatch === "gradient" && (
            <>
              <Form.Item
                label="渐变开始颜色"
                name="PPtBgValue1"
                rules={[{ required: true, message: "不得为空" }]}
              >
                <Input style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item
                label="渐变结束颜色"
                name="PPtBgValue2"
                rules={[{ required: true, message: "不得为空" }]}
              >
                <Input style={{ width: "100%" }} />
              </Form.Item>
            </>
          )} */}
        </Form>
      </Drawer>
    </div>
  );
};

export default PPTDisplayList;
